package io;


import util.Point;

import java.io.IOException;
import java.util.StringTokenizer;

import ship.Ship;

import main.Constants;
import main.Game;
import main.ThinGame;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryonet.*;

public class Network {
	private Server server = new Server();
	private Client client = new Client();
	private boolean isServer;


	
	public Network() {
		isServer = true;
		
		try {
			server.start();
			server.bind(54555, 54777);
			server.addListener(new Listener() {
				public void received(Connection connection, Object object) {
					//System.out.println(object);
					if(object instanceof String) {
						receiveCommand((String) object);
					}
				}
			});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Network(String ip) {
		isServer = false;
		try {
			client.start();
			client.connect(5000, ip, 54555, 54777);
			client.addListener(new Listener() {
				public void received(Connection connection, Object object) {
					if(object instanceof String) {
						receiveCommand((String)object);
					}
				}
			});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendMessage(String s) {
			if(isServer) {
				server.sendToAllTCP(s);
			}
			else {
				client.sendTCP(s);
			}
	}

	
	public void receiveCommand(String s) {
		try {
			if(isServer) {
				Game.game.recieveMessage(s);
			}
			else {
				ThinGame.game.recieveMessage(s);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
	}
}

